import cv2
import time

def run():
    # Open the default camera (usually camera index 0)
    cap = cv2.VideoCapture(0)
    
    if not cap.isOpened():
        print("Error: Could not open camera.")
        return
    
    # Get and print video properties
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = cap.get(cv2.CAP_PROP_FPS)
    
    print(f"Video Resolution: {width} x {height}")
    print(f"Frame Rate: {fps:.2f} FPS")
    
    while True:
        # Capture frame-by-frame
        ret, frame = cap.read()
        
        if not ret:
            print("Error: Could not read frame.")
            break
        
        # Display the resulting frame
        cv2.imshow('Camera Feed', frame)
        
        # Press 'q' to quit
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    # When everything done, release the capture
    cap.release()
    cv2.destroyAllWindows()

def run_time():
    # 打开默认摄像头（通常是索引0）
    cap = cv2.VideoCapture(0)
    
    if not cap.isOpened():
        print("错误：无法打开摄像头。")
        return
    
    # 获取视频属性
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = cap.get(cv2.CAP_PROP_FPS)
    
    # 如果无法获取FPS（常见于摄像头），则手动计算
    if fps <= 0:
        fps = 30.0  # 默认值
    
    prev_time = time.time()
    font = cv2.FONT_HERSHEY_SIMPLEX
    
    while True:
        # 逐帧捕获
        ret, frame = cap.read()
        
        if not ret:
            print("错误：无法读取帧。")
            break
        
        # 计算实时FPS
        current_time = time.time()
        actual_fps = 1 / (current_time - prev_time)
        prev_time = current_time
        
        # 在画面上显示信息
        cv2.putText(frame, f"resolution: {width}x{height}", (10, 30), font, 0.7, (0, 255, 0), 2)
        cv2.putText(frame, f"FPS: {actual_fps:.1f}", (10, 60), font, 0.7, (0, 255, 0), 2)
        
        # 显示结果帧
        cv2.imshow('实时摄像头', frame)
        
        # 按'q'退出
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    # 释放摄像头并关闭窗口
    cap.release()
    cv2.destroyAllWindows()

def main():
    run_time()
    # run()

if __name__ == "__main__":
    main()